package top.waikin.aspect.component;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author WaiKin
 * @date 2022/11/27
 */
@Slf4j
@Component
public class CacheManager {
  private static final String TTL_SUFFIX = "_ttl";
  private final Map<String, Object> cache = new HashMap<>();

  public void set(String key, Object value, long ttl) {
    log.info("set:key:{},value:{},ttl:{}", key, value, ttl);
    cache.put(key, value);
    if (ttl == -1) {
      cache.put(key + TTL_SUFFIX, -1);
    } else {
      cache.put(key + TTL_SUFFIX, System.currentTimeMillis() + ttl * 1000);
    }
  }

  public Object get(String key) {
    log.info("get:{}", key);
    if (containsKey(key)) {
      return cache.get(key);
    }
    return null;
  }

  public void remove(String key) {
    log.info("remove:{}", key);
    cache.remove(key);
    cache.remove(key + TTL_SUFFIX);
  }

  public boolean containsKey(String key) {
    log.info("contains:{}", key);
    Long ttl = (Long) cache.get(key + TTL_SUFFIX);
    if (ObjectUtil.isNull(ttl)) {
      return false;
    }
    if (ttl == -1 || ttl >= System.currentTimeMillis()) {
      return true;
    }
    remove(key);
    return false;
  }
}
